# -*-coding:utf-8-*-

import base64
import json
import time

from Crypto import Random
from Crypto.Cipher import AES

app_key = '93F9C5720748E3F37F591D295EF61A8A'
app_id = '6194C5C4A27A0AFF0AED6F63A3C9B7DF'
wx_mp_openid = 'your_wx_mp_openid'
domain = 'wx.hifocus.top'


def generate_token(appkey, user_id, expires_in=3600, token_args={}):
    AES_KEY = app_id
    iv = Random.new().read(AES.block_size)
    cipher = AES.new(AES_KEY, AES.MODE_CFB, iv)
    expires_at = time.time() + expires_in
    # plain_text = '%s:%s:%f' % (user_id, group_id, expire_at)
    plain_text = '%s:%f:%s' % (user_id, expires_at, base64.urlsafe_b64encode(json.dumps(token_args)))
    cipher_text = cipher.encrypt(plain_text)
    access_token = iv + str(appkey) + cipher_text
    return base64.urlsafe_b64encode(access_token), int(expires_at)


def get_bind_token():
    user_id = wx_mp_openid
    token_args = {}
    token_args['user_bind_data'] = {
        'weixin': {
            'mp': {
                'openid': wx_mp_openid,
            }
        }
    }
    token_args['domain'] = domain
    access_token, unused = generate_token(app_key, user_id, token_args=token_args)
    return access_token


def get_access_token():
    user_id = '5932177c95004c3a687ea924'
    user_id = '5932177c95004c3a687ea925'
    expires_in=3600 * 24 * 60
    access_token, unused = generate_token(app_key, user_id, expires_in=expires_in)
    return access_token


if '__main__' == __name__:
    bind_token = get_bind_token()
    print bind_token
    access_token = get_access_token()
    print access_token
